from DrissionPage import ChromiumPage, SessionPage
from time import sleep
from typing import Callable
import sys, os
from util import file_helper
from util import my_tkinter


def hqxbqy_获取新标签页(page: ChromiumPage, title: str, time: int):
    wait_time = 0.1
    time = time / wait_time
    for i in range(1, int(time)):
        tab = page.get_tab(title=title)
        if tab != None:
            return tab
        sleep(wait_time)
    return None


def get_tabs_titles_获取所有标签的标题(page: ChromiumPage):
    lis_tabs = page.get_tabs()
    lis_titles = []
    for tab in lis_tabs:
        title = tab.title
        lis_titles.append(title)
    return lis_titles


def hqxbqy_网页操作_获取新标签页(page: ChromiumPage, fun, title: str, time: int):
    wait_time = 0.1
    time = time / wait_time
    lis_titles = get_tabs_titles_获取所有标签的标题(page)
    fun(page)
    for i in range(1, int(time)):
        lis_titles_new = get_tabs_titles_获取所有标签的标题(page)
        if len(lis_titles) != len(lis_titles_new):
            if title in lis_titles_new:
                tab = page.get_tab(title=title)
                return tab
        sleep(wait_time)
        # else:
        # return None
    return None


class xz_下载_class:
    def __init__(self) -> None:
        self.page = SessionPage()

    def xzwj_下载文件(self, url: str, folder_path: str, file_qz):
        # file_helper.scwj_删除文件(file_name=file_name, folder_path=folder_path)
        file_helper.gjwjmqzscwj_根据文件名前缀删除文件(
            file_qz=file_qz, folder_path=folder_path
        )

        # self.page = SessionPage()
        # 保存原始标准输出
        original_stdout = sys.stdout
        # 创建一个空的文件对象
        sys.stdout = open(os.devnull, "w")
        self.page.download(url, goal_path=folder_path, rename=file_qz)
        # 恢复标准输出
        sys.stdout.close()
        sys.stdout = original_stdout

    def close(self):
        self.page.close()


def tzym_跳转页面(url: str, page: ChromiumPage, str_xpath: str):
    i = 0
    while True:
        print(73)
        i += 1
        page.get(url)
        page.wait.doc_loaded()
        e = page.ele(str_xpath, timeout=0)
        if e:
            break
        elif i >= 10:
            my_tkinter.文本框("可能出现验证码")
        sleep(1)
        # if not e:
        #     my_tkinter.文本框("可能出现验证码")
        # else:
        #     break
